﻿using Nest;
using System;
using System.Collections.Generic;

namespace EsSample
{
    public class LogService
    {
        private static readonly string _logIndex = "idx_abc";

        private static List<dynamic> FakeData()
        {
            var values = new List<dynamic>();
            for (var i = 1; i <= 30; i++)
            {
                dynamic obj = new System.Dynamic.ExpandoObject();
                obj.no = i;
                obj.id = $"id_{i}";
                obj.message = $"log message {i}.";
                obj.created = DateTime.Now.AddMinutes(-i);
                values.Add(obj);
            }

            return values;
        }
        public static void Write()
        {
            var descriptor = new BulkDescriptor();
            foreach (var doc in FakeData())
            {
                descriptor.Index<object>(i => i
                    .Index(_logIndex)
                    .Id((Id)doc.id)
                    .Document((object)doc));
            }
            var client = EsClientFactory.GetClient;
            client.Bulk(descriptor);
        }

        public static ISearchResponse<dynamic> Read()
        {
            var client = EsClientFactory.GetClient;

            var result = client.Search<dynamic>(s => s
                .Index(_logIndex)
                .From(0)
                .Size(10)
                .MatchAll()
                .Sort(st => st
                    .Field(f => f
                        .Field("no")
                        .Order(SortOrder.Descending)
                    )
                )
            );
            return result;
        }

        public static GetResponse<dynamic> ReadById(string id)
        {
            var client = EsClientFactory.GetClient;
            var log = client.Get<dynamic>(id, g => g.Index(_logIndex));
            return log;
        }
    }
}
